package com.house.util;

import com.qcloud.cos.COSClient;
import com.qcloud.cos.model.CannedAccessControlList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.UUID;

@Component
public class COSUtil {

    @Autowired
    private COSClient client;

    @Value("${tencent.cos.buckerName}")
    public String buckerName;

    @Value("${tencent.cos.url}")
    public String url;

    public String upload(MultipartFile file) {
        try {
            String filename = file.getOriginalFilename();
            if (filename == null) {
                throw new RuntimeException();
            }
            InputStream stream = file.getInputStream();
            String filePath = getFilePath(filename);

            client.putObject(buckerName,filePath,stream,null);
            client.setBucketAcl(buckerName, CannedAccessControlList.PublicRead);

            return url + "/" + filePath;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private String getFilePath(String filename) {
        String suffix = filename.substring(filename.lastIndexOf("."));
        return UUID.randomUUID() + suffix;
    }

}
